# SPDX-License-Identifier: BSD-2-Clause

import os

from migen import *
from litex.gen import *
from litex.soc.interconnect import wishbone
#from litex.build.io import SDRTristate

# IrDA Wishbone -----------------------------------------------------------------------------------------

class IRDA(LiteXModule):
    def __init__(self, platform, pads):

        self.pads    = pads
        self.wb_ctrl = wb_ctrl = wishbone.Interface(data_width=32, address_width=32, addressing="word")

        self.interrupt = Signal()


        # # #

        # IrDA Wishbone Core Instance.
        self.specials += Instance(self.get_netlist_name(),
            # Clk / Rst.
            i_wb_clk_i   = ClockSignal("sys"),
            i_wb_rst_i   = ResetSignal("sys"),
            # Wishbone Control.
            i_wb_cyc_i   = wb_ctrl.cyc,
            i_wb_adr_i   = wb_ctrl.adr,
            i_wb_dat_i   = wb_ctrl.dat_w,
            i_wb_sel_i   = wb_ctrl.sel,
            i_wb_we_i    = wb_ctrl.we,
            i_wb_stb_i   = wb_ctrl.stb,
            o_wb_dat_o   = wb_ctrl.dat_r,
            o_wb_ack_o   = wb_ctrl.ack,
            # Interrupt.
            o_int_o      = self.interrupt,
            # pads.
            i_rx_pad_i   = pads.rx,
            o_tx_pad_o   = pads.tx,
        )


        self.add_sources(platform)

    def get_netlist_name(self):
        return "irda_top" 

    def add_sources(self, platform):

        cdir = os.path.abspath('.')
        vdir = os.path.join(cdir, "IRDA_WB", "sim")
        netlist_name = self.get_netlist_name()

        print(f"IrDA netlist : {netlist_name}")
        if not os.path.exists(os.path.join(vdir, netlist_name + ".v")):
            self.generate_netlist()

        platform.add_source(os.path.join(vdir,  netlist_name + ".v"), "verilog")

    def generate_netlist(self):
        print(f"Generating IrDA netlist")
        sources = []
        sdir = "IRDA_WB"
        if not os.path.exists(sdir):
            os.system(f"git clone git://repogit.moditek/irda.git IRDA_WB")

        cdir = os.path.abspath('.')

        cmd = 'cd {path} && bash merge_rtl.cmd'.format(
            path=os.path.join(cdir, "IRDA_WB", "sim") )
        print("!!! "   + cmd)
        if os.system(cmd) != 0:
            raise OSError('Failed to run merge_rtl.cmd')

